/**
 * 
 */
package dao.versant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.jdo.Extent;
import javax.jdo.Query;

import dao.interfaces.IVilleDAO;

import tp.model.Train;
import tp.model.Trajet;
import tp.model.Ville;

/**
 * @author Admin
 * 
 */
public class VilleDAOVersant extends VersantDAO<Ville> implements IVilleDAO {

	@Override
	public Ville find(String nomVille) {
		Query q = pm.newQuery(Ville.class);
		q.declareParameters("String ville");
		q.setFilter("nom == ville");
		Ville ville = null;
		Collection collection;
		try {
			collection = (Collection) q.execute(nomVille);
			if (!collection.isEmpty()) {
				Iterator i = collection.iterator();
				if (i.hasNext())
					ville = (Ville) i.next();
			}
		} finally {
			if (ville != null) q.close(ville);
		}
		return ville;
	}

	@Override
	public ArrayList<Ville> findAllDesservie(String nomVille) {
		Query q = pm.newQuery(Trajet.class);
		q.declareParameters("String v");
		q.setFilter("depart.nom == v");
        q.setOrdering("arrivee descending");
		ArrayList<Trajet> listTrajets = new ArrayList<Trajet>();
		ArrayList<Ville> listVilles = new ArrayList<Ville>();
		Collection collection;
		try {
			collection = (Collection) q.execute(nomVille);
			if (!collection.isEmpty()) {
				Iterator i = collection.iterator();
				while (i.hasNext()) {
					listTrajets.add((Trajet) i.next());
				}
			}
			Ville arrivee = null;
			for (Trajet t : listTrajets) {
				if (arrivee != t.getArrivee()) {
					listVilles.add(t.getArrivee());
					arrivee = t.getArrivee();
				}
			}
		} finally {
			if (listTrajets != null) q.close(listTrajets);
		}
		return listVilles;
	}
	
	@Override
	public ArrayList<Ville> findAll() {
		ArrayList<Ville> listVilles = new ArrayList<Ville>();
		Extent e = pm.getExtent(Ville.class, true);
		Iterator iter = e.iterator();
		while (iter.hasNext()) {
			listVilles.add((Ville) iter.next());
		}
		return listVilles;
	}
	
	@Override
	public void create(Ville ville) {
		pm.currentTransaction().begin();
		pm.makePersistent(ville);
		pm.currentTransaction().commit();
	}

	@Override
	public void delete(Ville obj) {

	}

}
